package com.onpositive.data.kvstorage;

import com.onpositive.data.IPropertyMetadata;
import com.onpositive.datamap.core.IDataCollection;
import com.onpositive.datamap.core.IDataProperty;
import com.onpositive.datamap.core.impl.DataCollection;
import com.onpositive.datamap.core.impl.DataProperty;
import com.onpositive.datamap.item.SingleDataObject;
import com.onpositive.datamap.values.impl.BasicValue;

public class KeyValueCollectionCreatorFacade {

	public static void storeCollection(IKeyValueCollectionCreator creator,
			IDataCollection collection,DataCollectionInfo info,IProgress p) {
		String alloc = creator.alloc(info.name);
		try {
			int count = collection.getCount();
			p.setTotal(count+10);
			for (int a = 0; a < count; a++) {
				p.progress(1);
				creator.store(alloc,
						new SingleDataObject(collection.getObject(a)));
			}
			DataCollection dc = (DataCollection) collection;
			IPropertyMetadata[] systemProperties = dc.getSystemProperties();
			for (IPropertyMetadata m : systemProperties) {
				if (m == null) {
					continue;
				}
				creator.addProperty(alloc, m);
				Object[] v = new Object[count];
				for (int a = 0; a < count; a++) {
					v[a] = dc.getCollection().getValue(a, m);
				}
				creator.storeIndex(alloc, m.id(), v);
			}
			IDataProperty[] properties = collection.getProperties();
			for (IDataProperty q : properties) {
				DataProperty mq=(DataProperty) q;
				creator.addProperty(alloc, mq.meta);
				Object[] mma = new Object[count];
				for (int a = 0; a < count; a++) {
					BasicValue value = (BasicValue) q.getValue(collection.getObject(a));
					if (value!=null){
						value=value.toTransferForm();
					}
					mma[a] = value;
				}
				creator.storeIndex(alloc,q.id(), mma);
			}
			creator.commit(alloc,info);
		} catch (Throwable e) {
			e.printStackTrace();
			creator.rollback(alloc);
		}
	}
}
